/*
    Copyright: Octavian Marius Chincisan 2012.
    main
*/
#include <openssl/md5.h>
#include <htmlcxx/html/ParserDom.h>
#include <memory>
#include <pcrecpp.h>
#include "strops.h"
#include "main.h"
#include "database.h"
#include "site.h"
#include "wcurl.h"
#include "config.h"
#include "glb.h"
#include "thr.h"

//-----------------------------------------------------------------------------
bool __alive = true;
void ControlC (int i)
{
    __alive = false;
    printf("Control C. Exiting... \n");
    usleep(0x1FFFFF);
}

//-------------------------------------------------------------------------------
void ControlP (int i)
{
    __alive=false;
    sleep(2);
}

//-----------------------------------------------------------------------------
int main(int nargs, char* vargs[])
{
    mutex       m;
    mysqlcls    db;

    signal(SIGINT,  ControlC);
    signal(SIGABRT, ControlC);
    signal(SIGKILL, ControlC);
    signal(SIGTRAP, SIG_IGN);
    signal(SIGPIPE, SIG_IGN); //this is crap

    Conf        config;
    GCFG=&config;
    config.load(vargs[0]);

    db.connect(config._mitza.host.c_str(),config._mitza.user.c_str(),config._mitza.password.c_str());

    if(nargs>1 && !::strcmp(vargs[1],"--create"))
    {
        cout << "creating database and fresh tables. Now run without any parameters\n";
        db.createtables();
        return 0;
    }

    vector<cthread*>         mt;

    for(int i=0;i<config._mitza.threads;i++)
    {
        cthread* pt = new cthread();
        pt->start_thread();
        mt.push_back(pt);
    }

    struct  stat    st;
    while(__alive)
    {
        if(stat(config._mitza.sitefile.c_str(), &st)==0)
        {
            if(st.st_size > 100)
            {
                char    line[256];

                FILE* pf = ::fopen(config._mitza.sitefile.c_str(),"rb");
                if(pf)
                {
                    while(!feof(pf))
                    {
                        fgets(line,255,pf);
                        so::trimcrlf(line);
                        if(::strstr(line,"S T O P"))
                        {
                            __alive=false;
                            break;
                        }
                        if(line[0]!='#')
                            glb::add_site(&db, &m, line);
                        if(::feof(pf))
                            break;
                    }
                    fclose(pf);
                    sleep(1);
                    pf = ::fopen(config._mitza.sitefile.c_str(),"wb");

                    ::fputs("#sn=website mxd=# reindex=# tit=title dsc=desc offs=0/1 yc=? lg=language pri=? cat=#\n",pf);
                    ::fclose(pf);
                }
            }
        }
        usleep(10000);
    }


    for(int i=0;i<config._mitza.threads;i++)
    {
        mt[i]->stop_thread();
        delete mt[i];
    }

    GLOGT("EXITING...\n");
}

